//
//  AccountVerifyController.m
//  onlineCustoSDK
//
//  Created by 曹宗华 on 2017/12/6.
//  Copyright © 2017年 com.netinfosz. All rights reserved.
//

#import "AccountVerifyController.h"

@interface AccountVerifyController ()

@end

@implementation AccountVerifyController

- (void)viewDidLoad {
    [super viewDidLoad];
    UILabel *titleView=[[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 25)];
    titleView.textColor=[UIColor whiteColor];
    titleView.text=@"您正在客户认证中...";
    titleView.font=[UIFont systemFontOfSize:17];
    self.navigationItem.titleView=titleView;
    self.view.backgroundColor=[UIColor whiteColor];
    [self.navigationController.navigationBar setBarTintColor:XZColor(50, 164,238)];
//    [[UINavigationBar appearance] setTintColor:XZColor(50, 164,238)];
    [self setUI];
//     __weak typeof(self) weakSelf = self;
//    [[YiChatClient shareInstance] getVerifycodeResult:^(NSData *data) {
//       NSLog(@"图片字节长度:%ld",data.length);
//        UIImage *image=[UIImage imageWithData:data];
//       [weakSelf.vefifyBtn setBackgroundImage:image forState:UIControlStateNormal];
//    }];
    [[YiChatClient shareInstance] getTokenSuccess:^(NSString *info) {
        NSLog(@"token:%@",info);
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if([returnDic[@"CODE"] intValue]==0)
        {
            [YiChatClient shareInstance].validateToken=returnDic[@"INFO"];
           self.validateToken=returnDic[@"INFO"];
            NSLog(@"validatetoken:%@",self.validateToken);
            
//            [[YiChatClient shareInstance] getValidateCodeSuccess:^(NSString *info) {
//                  NSLog(@"获取验证码:%@",info);
//                NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
            
//            }];
            UIImage *codeImage=[[YiChatClient shareInstance] getValidateCodeWithToken:self.validateToken];
            [_vefifyBtn setImage:codeImage forState:UIControlStateNormal];
            
        }
        
    }];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setUI
{
    UIButton *backBtn=[[UIButton alloc] init];
    backBtn.frame=CGRectMake(0, 0, 10, 20);
    [backBtn.widthAnchor constraintEqualToConstant:10].active=YES;
    [backBtn.heightAnchor constraintEqualToConstant:20].active=YES;
//     backBtn.contentMode=UIViewContentModeScaleToFill;
//    UIButton *backBtn=[[UIButton alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
//    [backBtn setBackgroundImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *backItem=[[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem=backItem;
//    self.navigationItem.backBarButtonItem=backItem;
    self.topLab.hidden=NO;
    self.acountLab.hidden=NO;
    self.acountField.hidden=NO;
    self.passwordLab.hidden=NO;
    self.passwordField.hidden=NO;
    self.confirmBtn.hidden=NO;
    self.cancelBtn.hidden=NO;
    self.verifyTextField.hidden=NO;
    self.vefifyBtn.hidden=NO;
    
}
- (void)backClick
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (UILabel*)topLab
{
    if (!_topLab) {
        _topLab=[[UILabel alloc] initWithFrame:CGRectMake(0, 64, App_Frame_Width, 30)];
        _topLab.textColor=XZColor(223, 100, 78);
        _topLab.text=@"座席001:您好!请问您办理的过程中有什么问题...";
        _topLab.font=[UIFont systemFontOfSize:14];
        _topLab.textAlignment=NSTextAlignmentCenter;
        [self.view addSubview:_topLab];
    }
    return _topLab;
}
- (UILabel*)acountLab
{
    if (!_acountLab) {
        _acountLab=[[UILabel alloc] initWithFrame:CGRectMake(30, 100, 150, 30)];
        _acountLab.text=@"资金账号";
        _acountLab.font=[UIFont systemFontOfSize:15];
        _acountLab.textAlignment=NSTextAlignmentLeft;
        [self.view addSubview:_acountLab];
        
    }
    return _acountLab;
}
- (UILabel*)passwordLab
{
    if (!_passwordLab) {
        _passwordLab=[[UILabel alloc] initWithFrame:CGRectMake(30, self.acountField.frame.origin.y+self.acountField.frame.size.height+20, 150, 30)];
       _passwordLab.text=@"交易密码";
//        _passwordLab.backgroundColor=[UIColor greenColor];
        _passwordLab.font=[UIFont systemFontOfSize:15];
        _passwordLab.textAlignment=NSTextAlignmentLeft;
        [self.view addSubview:_passwordLab];
    }
    return _passwordLab;
}
- (UITextField*)acountField
{
    if(!_acountField)
    {
        _acountField=[[UITextField alloc] initWithFrame:CGRectMake(30, self.acountLab.frame.origin.y+self.acountLab.frame.size.height+10, App_Frame_Width-60, 35)];
        _acountField.delegate=self;
        _acountField.placeholder=@"请输入资金帐号";
        _acountField.tag=0x001001;
        _acountField.borderStyle=UITextBorderStyleRoundedRect;
        _acountField.textAlignment=NSTextAlignmentLeft;
        [self.view addSubview:_acountField];
        
    }
    return _acountField;
}
- (UITextField*)passwordField
{
    if(!_passwordField)
    {
        _passwordField=[[UITextField alloc] initWithFrame:CGRectMake(30, self.passwordLab.frame.origin.y+self.passwordLab.frame.size.height+10, App_Frame_Width-60, 35)];
        _passwordField.delegate=self;
        _passwordField.placeholder=@"请输入交易密码";
        _passwordField.tag=0x001002;
        _passwordField.secureTextEntry=YES;
        _passwordField.borderStyle=UITextBorderStyleRoundedRect;
        _passwordField.textAlignment=NSTextAlignmentLeft;
        [self.view addSubview:_passwordField];
        
    }
    return _acountField;
}
- (UITextField*)verifyTextField
{
    if (!_verifyTextField)
    {
        _verifyTextField=[[UITextField alloc] initWithFrame:CGRectMake(30, APP_Frame_Height*0.45, App_Frame_Width*0.4, 35)];
        _verifyTextField.delegate=self;
        _verifyTextField.placeholder=@"请输入验证码";
        _verifyTextField.tag=0x001003;
        _verifyTextField.borderStyle=UITextBorderStyleRoundedRect;
        _verifyTextField.textAlignment=NSTextAlignmentLeft;
        [self.view addSubview:_verifyTextField];
    }
    return _verifyTextField;
}
- (UIButton*)vefifyBtn
{
    if (!_vefifyBtn)
    {
        _vefifyBtn=[[UIButton alloc] init];
        _vefifyBtn.frame=CGRectMake(self.verifyTextField.frame.origin.x+self.verifyTextField.frame.size.width+20, self.verifyTextField.frame.origin.y, 60, 35);
        _vefifyBtn.contentMode =UIViewContentModeScaleToFill;
        [_vefifyBtn addTarget:self action:@selector(getVefifyCode) forControlEvents:UIControlEventTouchUpInside];
       _vefifyBtn.backgroundColor=[UIColor lightGrayColor];
        [self.view addSubview:_vefifyBtn];
    }
    return _vefifyBtn;
}
- (void)getVefifyCode
{
      UIImage *image=[[YiChatClient shareInstance] getValidateCodeWithToken:[YiChatClient shareInstance].validateToken ];
    [_vefifyBtn setImage:image forState:UIControlStateNormal];
    
    
}
- (UIButton*)confirmBtn
{
    if(!_confirmBtn)
    {
        _confirmBtn=[[UIButton alloc] init];
        _confirmBtn.frame=CGRectMake(30, APP_Frame_Height*0.65, App_Frame_Width-60, 40);
        [_confirmBtn setTitle:@"确认" forState:UIControlStateNormal ];
        [_confirmBtn setTintColor:[UIColor whiteColor]];
        _confirmBtn.backgroundColor=XZColor(50, 164,238);
        _confirmBtn.layer.masksToBounds=YES;
        _confirmBtn.layer.cornerRadius=5;
        [_confirmBtn addTarget:self action:@selector(confirmOK) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_confirmBtn];
    }
    return _confirmBtn;
}
- (UIButton*)cancelBtn
{
    if(!_cancelBtn)
    {
        _cancelBtn=[[UIButton alloc] init];
        _cancelBtn.frame=CGRectMake(30, self.confirmBtn.frame.origin.y+self.confirmBtn.frame.size.height+20, App_Frame_Width-60, 40);
        [_cancelBtn setTitle:@"放弃" forState:UIControlStateNormal ];
//        [_cancelBtn setTintColor:[UIColor blackColor]];
        [_cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
//        _cancelBtn.backgroundColor=XZColor(50, 164,238);
        _cancelBtn.layer.masksToBounds=YES;
        _cancelBtn.layer.cornerRadius=5.0;
        _cancelBtn.layer.borderColor=XZColor(50, 164,238).CGColor;
        [_cancelBtn.layer setBorderWidth:1.0];
        [_cancelBtn addTarget:self action:@selector(cancelClicked) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_cancelBtn];
    }
    return _cancelBtn;
}
- (void)confirmOK
{
    NSLog(@"参数:%@,%@,%@,%@,%@",self.accountNum,self.password,[YiChatClient shareInstance].custAcctType,self.validateCode,[YiChatClient shareInstance].validateToken);
    
//    NSString *publicKey=[NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"pubkey" ofType:@"key"]];
    
    NSBundle *bundle=[NSBundle bundleWithIdentifier:onlineCustoSDK_IOS_FRAMEWORK_BUNDLE_ID];
//    NSURL *URL=[bundle URLForResource:@"pubkey" withExtension:@"key"];
    NSString *path =  [bundle pathForResource:@"pubkey" ofType:@"key"];
//    NSString *path= [[NSBundle mainBundle] pathForResource:@"123" ofType:@"plist"];
     NSLog(@"path:%@",path);
    NSString *publicKey2 =[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSString *publicKey = @"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCzAtERdsniZVQQ+QRYlcFW5RBUE0Vo+AcGp25PQR9B5cyEkiZAUQCf6d8Y1y/r4/Wkmf33BpChKLuHRrmKgHQ6ZGbcss/TaMwCakzue91ezFMHeYuzWFwgqbFlM2q+cH+uS1HuG5tm+2a3axMaQ9+UdvyRxht29x2YbP1ztovamQIDAQAB";
    NSLog(@"publicKey2:%@",publicKey2);
// [self encode:publicKey]
    NSString *encriptpassword = [RSAUtil encryptString:self.password publicKey:publicKey];
    NSLog(@"encriptpassword:%@",encriptpassword);
    
//    [[YiChatClient shareInstance] validateAount:self.accountNum password:encriptpassword Success:^(NSString *info) {
//        NSLog(@"验证结果:%@",info);
//        [CCDemoUtil showAlertWithTitle:@"提示" content:info];
////        [self.navigationController popViewControllerAnimated:YES];
//    } fail:^(NSError *error) {
//
//    }];
    NSLog(@"validateToken2:%@",self.validateToken);
    /**
    - (void)validateAount:(NSString*)custAcctNo password:(NSString*)password ValidateCode:(NSString*)validatecode CustAcctType:(NSString*)custAcctType Token:(NSString*)token PubKey:(NSString*)pubkey Syscode:(NSString*)systemcode Need:(BOOL)feedBack Success:(successBlock)sucBlock fail:(failureBlock)failBlock
     **/
    [[YiChatClient shareInstance] validateAount:self.accountNum password:self.password ValidateCode:self.validateCode CustAcctType:@"Z" Token:self.validateToken PubKey:publicKey Syscode:nil Need:YES Success:^(NSString *info) {
         NSLog(@"验证结果:%@",info);
         [CCDemoUtil showAlertWithTitle:@"提示" content:info];
        NSData *data=[info dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *returnDic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        if([returnDic[@"CODE"] intValue]==0)
        {
            NSLog(@"验证成功");
//            NSString *successInfo=returnDic[@"INFO"];
//            NSDictionary *contentDic=@{@"appid":@"14007",@"className":@"text-green",@"content":@"验证成功",@"custAcctType":@"Z",@"custid":successInfo,@"msgType":@"custVerify",@"param":@"",@"password":@"",@"phoneNum":@"xxh",@"verifyRes":@(1),@"sendToAgent":@"true"};
//            NSString *content=[contentDic jsonString];
//            [[YiChatClient shareInstance] sendMessage:content type:@"custVerify"];
        }
    } fail:^(NSError *error) {

    }];
    
    
}
- (void)cancelClicked
{
     [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSLog(@"return键点击了...");
    if (textField.tag==0x001001) {
        self.accountNum=self.acountField.text;
    }
     if(textField.tag==0x001002)
    {
        self.password=self.passwordField.text;
    }
    if(textField.tag==0x001003)
    {
        self.validateCode=textField.text;
        [YiChatClient shareInstance].validateCode=self.validateCode;
    }
    [textField resignFirstResponder];//辞去第一响应
    return YES;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    NSLog(@"%@", textField.text);//文本变化内容
    return YES;
}
- (BOOL)textFieldShouldClear:(UITextField *)textField
{
     NSLog(@"clear button被点击了...");
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
     NSLog(@"开始输入...");
}
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    NSLog(@"输入结束...");
    if (textField.tag==0x001001)
    {
        self.accountNum=textField.text;
        NSLog(@"帐号:%@",self.accountNum);
    }
        if(textField.tag==0x001002)
    {
        self.password=textField.text;
         NSLog(@"密码:%@",self.password);
    }
    if(textField.tag==0x001003)
    {
        self.validateCode=textField.text;
        [YiChatClient shareInstance].validateCode=self.validateCode;
    }
}
- (NSString *)encode:(NSString *)string
{
    //先将string转换成data
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    NSData *base64Data = [data base64EncodedDataWithOptions:0];
    
    NSString *baseString = [[NSString alloc]initWithData:base64Data encoding:NSUTF8StringEncoding];
    
    return baseString;
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
